package com.yunfeng.common.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yunfeng.common.dao.RoleDAO;
import com.yunfeng.common.entity.impl.Role;
import com.yunfeng.common.service.RoleService;
import com.yunfeng.common.shiro.ShiroDbRealm;
import com.yunfeng.common.util.Page;
import com.yunfeng.common.util.PageUtils;

/**
 * 
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleDAO roleDAO;

	@Autowired(required = false)
	private ShiroDbRealm shiroRealm;

	@Override
	public void save(Role role) {
		roleDAO.save(role);
	}

	@Override
	public Role get(Long id) {
		return roleDAO.findOne(id);
	}

	@Override
	public List<Role> findAll(Page page) {
		org.springframework.data.domain.Page<Role> springDataPage = roleDAO
				.findAll(PageUtils.createPageable(page));
		page.setTotalCount(springDataPage.getTotalElements());
		return springDataPage.getContent();
	}

	/**
	 * @param role
	 * @see com.yunfeng.common.service.RoleService#update(com.yunfeng.common.entity.impl.Role)
	 */
	public void update(Role role) {
		roleDAO.save(role);
		shiroRealm.clearAllCachedAuthorizationInfo();
	}

	/**
	 * @param id
	 * @see com.yunfeng.common.service.RoleService#delete(java.lang.Long)
	 */
	public void delete(Long id) {
		roleDAO.delete(id);
		shiroRealm.clearAllCachedAuthorizationInfo();
	}

	/**
	 * @param page
	 * @param name
	 * @return
	 */
	public List<Role> find(Page page, String name) {
		org.springframework.data.domain.Page<Role> springDataPage = (org.springframework.data.domain.Page<Role>) roleDAO
				.findByNameContaining(name, PageUtils.createPageable(page));
		page.setTotalCount(springDataPage.getTotalElements());
		return springDataPage.getContent();
	}

}
